
/** 
 * You can use this map like this:
 * var myMap = new Map();
 * myMap.put("key","value");
 * var key = myMap.get("key");
 * myMap.remove("key");
 */
function ArrayMap() {
     this.elements = new Array(); 
     //获取MAP元素个数
     this.size = function() {
         return this.elements.length;
     };
 
     //判断MAP是否为空
     this.isEmpty = function() {
         return (this.elements.length < 1);
     };
 
     //删除MAP所有元素
     this.clear = function() {
         this.elements = new Array();
     };
   //删除指定KEY的元素，成功返回True，失败返回False
     this.removeByKey = function(_key) {
         var bln = false;
         try {
             for (var i = 0; i < this.elements.length; i++) {
                 if (this.elements[i].key == _key) {
                     this.elements.splice(i, 1);
                     return true;
                 }
             }
         } catch (e) {
             bln = false;
         }
         return bln;
     };
     
     //向MAP中增加元素（key, value) 
     this.put = function(_key, _value) {
    	 this.removeByKey(_key);
         this.elements.push( {
             key : _key,
             value : _value
         });
     };
 
     
     //删除指定VALUE的元素，成功返回True，失败返回False
     this.removeByValue = function(_value) {//removeByValueAndKey
         var bln = false;
         try {
             for (var i = 0; i < this.elements.length; i++) {
                 if (this.elements[i].value == _value) {
                     this.elements.splice(i, 1);
                     return true;
                 }
             }
         } catch (e) {
             bln = false;
         }
         return bln;
     };
      
 
     //获取指定KEY的元素值VALUE，失败返回NULL
     this.get = function(_key) {
         try {
             for (var i = 0; i < this.elements.length; i++) {
                 if (this.elements[i].key == _key) {
                     return this.elements[i].value;
                 }
             }
         } catch (e) {
             return null;
         }
         return null;
     };
 
     //获取指定索引的元素（使用element.key，element.value获取KEY和VALUE），失败返回NULL
     this.element = function(_index) {
         if (_index < 0 || _index >= this.elements.length) {
             return null;
         }
         return this.elements[_index];
     };
 
     //判断MAP中是否含有指定KEY的元素
     this.containsKey = function(_key) {
         var bln = false;
         try {
             for (var i = 0; i < this.elements.length; i++) {
                 if (this.elements[i].key == _key) {
                    return true;
                 }
             }
         } catch (e) {
             bln = false;
         }
         return bln;
     };
 
     //判断MAP中是否含有指定VALUE的元素
     this.containsValue = function(_value) {
         var bln = false;
         try {
             for (var i = 0; i < this.elements.length; i++) {
                 if (this.elements[i].value == _value) {
                     return true;
                 }
             }
         } catch (e) {
             bln = false;
         }
         return bln;
     };
      
 
     //获取MAP中所有VALUE的数组（ARRAY）
     this.values = function() {
         var arr = new Array();
         for (var i = 0; i < this.elements.length; i++) {
             arr.push(this.elements[i].value);
         }
         return arr;
     };
      
 
     //获取MAP中所有KEY的数组（ARRAY）
     this.keys = function() {
         var arr = new Array();
         for (var i = 0; i < this.elements.length; i++) {
             arr.push(this.elements[i].key);
         }
         return arr;
     };
     
     //获取key通过value
     this.keysByValue = function(_value) {
         var arr = new Array();
         for (var i = 0; i < this.elements.length; i++) {
             if(_value == this.elements[i].value){
                 arr.push(this.elements[i].key);
             }
         }
         return arr;
     };
      
 }



+function ($) {
    'use strict';
    
	 $.extend(Function.prototype, { 
        toFunc: function() {
            return this
        },
		ligerDefer:function (o, defer, args)
		{
			var fn = this;
			return setTimeout(function () { fn.apply(o, args || []); }, defer);
		}
    });
	
	$.extend(kui,
	{ 
		// something-----------------------------------
		/**
		 * 判断是否IE
		 * @return {Boolean}
		 */
		isIE : function() {
			return /MSIE/i.test(navigator.userAgent);
		},
		/**
		 * 是否是chrome
		 * @return {Boolean}
		 */
		isChrome : function() {
			return /Chrome/i.test(navigator.userAgent);
		},
		isWebKit : function() {
			return /WebKit/i.test(navigator.userAgent);
		},
		/**
		 * 是否是火狐
		 * @return {Boolean}
		 */
		isFirefox : function() {
			return /Firefox/i.test(navigator.userAgent);
		},
		/**
		 * 是否已定义
		 * @param {Object}
		 * @return {Boolean}
		 */
		isDefined : function(o) {
			return typeof (o) != "undefined";
		},
		/**
		 * 是否是字符串
		 * @param {Object}
		 * @return {Boolean}
		 */
		isStr : function(o) {
			return typeof (o) == "string";
		},
		/**
		 * 是否数字
		 * @param {Object}
		 * @return {Boolean}
		 */
		isNum : function(o) {
			return isFinite(o)
		},
		/**
		 * 是否是日期
		 * @param {Object}
		 * @return {Boolean}
		 */
		isDate : function(o) {
			return (null != o) && !isNaN(o) && ("undefined" !== typeof o.getDate);
		},
		/**
		 * 是否是对象类型
		 * @param {Object}
		 * @return {Boolean}
		 */
		isObj : function(o) {
			return !!(o && typeof (o) == "object" );
		},
		/**
		 * 是否是方法类型
		 * @param {Object}
		 * @return {Boolean}
		 */
		isFn : function(o) {
			return !!(o && typeof (o) == "function");
		},
		/**
		 * 是否是可以迭代
		 * @param {Object}
		 * @return {Boolean}
		 */
		isAry : function(o) {
			var me = this;
			return !!(o && (o.constructor && o.constructor.toString().indexOf("Array") > -1 || me.isNodeList(o)));
		},
		/**
		 * 是否是节点列表
		 * @param {Object}
		 * @return {Boolean}
		 */
		isNodeList : function(o) {
			return !!(o && (o.toString() == '[object NodeList]' || o.toString() == '[object HTMLCollection]' || (o.length && this.isNode(o[0]))));
		},
		/**
		 * 是否是节点
		 * @param {Object}
		 * @return {Boolean}
		 */
		isNode : function(o) {
			return !!(o && o.nodeType);
		},
		/**
		 * 一个字符串能否根据空格拆分成一个数组，数组内元素个数大于1
		 * @param {String}
		 * @return {Boolean}
		 */
		isCanSplit2Ary : function(o, sign) {
			var me = this;
			return me.isStr(o) && o.split(sign || /\s+/g).length > 1;
		},
		/**
		 * 是否为空
		 * @param {Object}
		 * @return {Boolean}
		 */
		isEmpty : function(o) {
			var me = this;
			return typeof (o) == "undefined" || o == null || (!me.isNode(o) && me.isAry(o) && o.length == 0 || (me.isStr(o) && o == ""));
		},
		// -----------------------------------string-----------------------------------
		/**
		 * 去除所有空格
		 * @param {String}
		 * @return {String}
		 */
		trimAll : function(str) {
			if(str == null) {
				return null;
			}
			str = str.toString();
			return str.replace(/\s+/ig, "");
		},
		// -----------------------------------array-----------------------------------
		/**
		 * 从一个数组里面剔除部分元素
		 * @param {String|Array}
		 * @return {Array}
		 */
		aryDel : function(ary, del) {
			var me = this;
			if(!me.isAry(ary)) {
				return;
			}
			if(me.isAry(del)) {
				for(var i = 0; i < del.length; i++) {
					me.aryDel(ary, del[i]);
				}
			} else {
				for(var j = 0; j < ary.length; j++) {
					if(ary[j] == del) {
						ary.splice(j, 1);
					}
				}
			}
			return ary;
		},
		/**
		 * 判断是否数组中是否存在参数
		 * @param {String|Array}
		 * @return {Boolean}
		 */
		inAry : function(ary, o) {
			var me = this, flag = false;
			if(!me.isAry(ary)) {
				return;
			}
			for(var i = 0; i < ary.length; i++) {
				if(me.isAry(o)) {
					for(var j = 0; j < o.length; j++) {
						if(ary[i] == o[j]) {
							flag = true;
							break;
						}
					}
				} else {
					if(ary[i] == o) {
						flag = true;
						break;
					}
				}
			}
			return flag;
		},
		/**
		 * 合并对象，后面所有的对象的属性都加到第一个身上
		 * @param {Object ...}
		 * @return {Object}
		 */
		merge : function() {
			var a = arguments;
			if(a.length < 2) {
				return;
			}
			if(a[0] != null) {
				for(var i = 1; i < a.length; i++) {
					for(var r in a[i]) {
						a[0][r] = a[i][r];
					}
				}
			}
			return a[0];
		},
		/**
		 * 合并对象，后面所有的对象的属性都加到第一个身上，注意，如果第一个有了，则不覆盖
		 * @param {Object ...}
		 * @return {Object}
		 */
		mergeIf : function() {
			var a = arguments;
			if(a.length < 2) {
				return;
			}
			for(var i = 1; i < a.length; i++) {
				for(var r in a[i]) {
					if(a[0][r] == null) {
						a[0][r] = a[i][r];
					}
				}
			}
			return a[0];
		},
		// -----------------------------------else-----------------------------------
		/**
		 * 返回随机数
		 * @private
		 */
		only : function() {
			var rnd = Math.random(10000);
			return new Date().getTime().toString() + '_' + rnd.toString().substr(2, 10);
		} ,
        getMaxIndexObj: function($elements) {
            var zIndex = 0, index = 0
            
            $elements.each(function(i) {
                var newZIndex = parseInt($(this).css('zIndex')) || 1
                
                if (zIndex < newZIndex) {
                    zIndex = newZIndex
                    index  = i
                }
            })
            
            return $elements.eq(index)
        },
        /**
         * 将表单数据转成JSON对象 用法：$(form).serializeJson() Author: K'naan
         */
        serializeJson: function () {
            var o = {}
            var a = this.serializeArray()
            
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]]
                    }
                    o[this.name].push(this.value || '')
                } else {
                   o[this.name] = this.value || ''
                }
            })
            
            return o
        },
        /**
         * 输出firebug日志
         * @param {Object} msg
         */
        log: function(msg) {
            return this.each(function() {
                if (console) console.log('%s: %o', msg, this)
            })
        },
		isJson: function(obj) {
        var flag = true
        
        try {
            flag = $.parseJSON(obj)
        } catch (e) {
            return false
        }
        return flag ? true : false
       },
       isTag: function(tn) {
           if (!tn) return false
           if (!$(this).prop('tagName')) return false
           return $(this)[0].tagName.toLowerCase() == tn ? true : false
       }
	}); 
	 
      
    /**
     * 扩展String方法
     */
    $.extend(String.prototype, {
        isPositiveInteger: function() {
            return (new RegExp(/^[1-9]\d*$/).test(this))
        },
        isInteger: function() {
            return (new RegExp(/^\d+$/).test(this))
        },
        isNumber: function() {
            return (new RegExp(/^([-]{0,1}(\d+)[\.]+(\d+))|([-]{0,1}(\d+))$/).test(this))
        },
        includeChinese: function() {
        	return (new RegExp(/[\u4E00-\u9FA5]/).test(this))
        },
        trim: function() {
            return this.replace(/(^\s*)|(\s*$)|\r|\n/g, '')
        },
        startsWith: function (pattern) {
            return this.indexOf(pattern) === 0
        },
        endsWith: function(pattern) {
            var d = this.length - pattern.length
            return d >= 0 && this.lastIndexOf(pattern) === d
        },
        replaceSuffix: function(index) {
            return this.replace(/\[[0-9]+\]/,'['+index+']').replace('#index#',index)
        },
        replaceSuffix2: function(index) {
            return this.replace(/\-(i)([0-9]+)$/, '-i'+ index).replace('#index#', index)
        },
        trans: function() {
            return this.replace(/&lt;/g, '<').replace(/&gt;/g,'>').replace(/&quot;/g, '"')
        },
        encodeTXT: function() {
            return (this).replaceAll('&', '&amp;').replaceAll('<','&lt;').replaceAll('>', '&gt;').replaceAll(' ', '&nbsp;')
        },
        replaceAll: function(os, ns) {
            return this.replace(new RegExp(os,'gm'), ns)
        },
        /*替换占位符为对应选择器的值*/ //{^(.|\#)[A-Za-z0-9_-\s]*}
        replacePlh: function($box) {
            $box = $box || $(document)
            return this.replace(/{\/?[^}]*}/g, function($1) {
                var $input = $box.find($1.replace(/[{}]+/g, ''))
                
                return $input && $input.val() ? $input.val() : $1
            })
        },
        replaceMsg: function(holder) {
            return this.replace(new RegExp('({.*})', 'g'), holder)
        },
        replaceTm: function($data) {
            if (!$data) return this
            
            return this.replace(RegExp('({[A-Za-z_]+[A-Za-z0-9_-]*})','g'), function($1) {
                return $data[$1.replace(/[{}]+/g, '')]
            })
        },
        replaceTmById: function(_box) {
            var $parent = _box || $(document)
            
            return this.replace(RegExp('({[A-Za-z_]+[A-Za-z0-9_-]*})','g'), function($1) {
                var $input = $parent.find('#'+ $1.replace(/[{}]+/g, ''))
                return $input.val() ? $input.val() : $1
            })
        },
        isFinishedTm: function() {
            return !(new RegExp('{\/?[^}]*}').test(this))
        },
        skipChar: function(ch) {
            if (!this || this.length===0) return ''
            if (this.charAt(0)===ch) return this.substring(1).skipChar(ch)
            return this
        },
        isValidPwd: function() {
            return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this))
        },
        isValidMail: function() {
            return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim()))
        },
        isSpaces: function() {
            for (var i = 0; i < this.length; i += 1) {
                var ch = this.charAt(i)
                
                if (ch!=' '&& ch!='\n' && ch!='\t' && ch!='\r') return false
            }
            return true
        },
        isPhone:function() {
            return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this))
        },
        isUrl:function() {
            return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this))
        },
        isExternalUrl:function() {
            return this.isUrl() && this.indexOf('://'+ document.domain) == -1
        },
        toBool: function() {
            return (this.toLowerCase() === 'true') ? true : false
        },
        toJson: function() {
            var json = this
            
            try {
                if (typeof json == 'object') json = json.toString()
                if (!json.trim().match("^\{(.+:.+,*){1,}\}$")) return this
                else return JSON.parse(this)
            } catch (e) {
                return this
            }
        },
        toObj: function() {
            var obj = null
            
            try {
                obj = (new Function('return '+ this))()
            } catch (e) {
                obj = this
                kui.debug('String toObj：Parse "String" to "Object" error! Your str is: '+ this)
            }
            return obj
        },
        /**
         * String to Function
         * 参数(方法字符串或方法名)： 'function(){...}' 或 'getName' 或 'USER.getName' 均可
         * Author: K'naan
         */
        toFunc: function() {
            if (!this || this.length == 0) return undefined
            //if ($.isFunction(this)) return this
            
            if (this.startsWith('function')) {
                return (new Function('return '+ this))()
            }
            
            var m_arr = this.split('.')
            var fn    = window
            
            for (var i = 0; i < m_arr.length; i++) {
                fn = fn[m_arr[i]]
            }
            
            if (typeof fn === 'function') {
                return fn
            }
            
            return undefined
        },
        setUrlParam: function(key, value) {
            var str = '', url = this
            
            if (url.indexOf('?') != -1)
                str = url.substr(url.indexOf('?') + 1)
            else
                return url + '?' + key + '=' + value
            
            var returnurl = '', setparam = '', arr, modify = '0'
            
            if (str.indexOf('&') != -1) {
                arr = str.split('&')
                
                for (var i in arr) {
                    if (arr[i].split('=')[0] == key) {
                        setparam = value
                        modify = '1'
                    } else {
                        setparam = arr[i].split('=')[1]
                    }
                    returnurl = returnurl + arr[i].split('=')[0] + '=' + setparam + '&'
                }
                
                returnurl = returnurl.substr(0, returnurl.length - 1)
                if (modify == '0') {
                    if (returnurl == str)
                        returnurl = returnurl + '&' + key + '=' + value
                }   
            } else {
                if (str.indexOf('=') != -1) {
                    arr = str.split('=')
                    if (arr[0] == key) {
                        setparam = value
                        modify = '1'
                    } else {
                        setparam = arr[1]
                    }
                    returnurl = arr[0] + '=' + setparam
                    if (modify == '0') {
                        if (returnurl == str)
                            returnurl = returnurl + '&' + key + '=' + value
                    }
                } else {
                    returnurl = key + '=' + value
                }
            }
            return url.substr(0, url.indexOf('?')) + '?' + returnurl
        }
    });
    
    /* Array */
    $.extend(Array.prototype, {
        remove: function(index) {
            if (index < 0) return this
            else return this.slice(0, index).concat(this.slice(index + 1, this.length))
        },
        unique: function() {
            var temp = new Array()
            
            this.sort()
            for (var i = 0; i < this.length; i++) {
                if (this[i] == this[i + 1]) continue
                temp[temp.length] = this[i]
            }
            
            return temp
        },
        myIndexOf: function(e) {
            if (!this || !this.length) return -1
            
            for (var i = 0, j; j = this[i]; i++) {
                if (j == e) return i
            }
            
            return -1
        },
        /* serializeArray to json */
        toJson: function() {
            var o = {}
            var a = this
            
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]]
                    }
                    o[this.name].push(this.value || '')
                } else {
                   o[this.name] = this.value || ''
                }
            })
            
            return o
        }
    })
      
}(jQuery);